package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.adapter.base.recyler.ItemWrapper;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerAdapter;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerHolder;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.bean.FoundDynamicBean;
import com.linjian.togetherbirthday.bean.HomeActivityDataBean;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.utils.AESOperator;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.sdsmdg.tastytoast.TastyToast;
import com.yuntongxun.plugin.common.common.utils.TextUtil;
import com.yuntongxun.plugin.im.manager.IMPluginManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class OnADateInfoFragment extends BaseFragment implements View.OnClickListener, XRecyclerView.LoadingListener {

    private ImageView backIv, userImgIv, rightIv, contactIv;
    private TextView userNameTv, userYearTv, contantTv, addressTv, timeTv, titleTv, rightTv, whyPayTv;
    private XRecyclerView mRecyclerView;
    private RecyclerAdapter<FoundDynamicBean.DataBean> mRecylerAdapter;
    private List<FoundDynamicBean.DataBean> mList;
    private TextView joinTv,appraiseTv;

    private HomeActivityDataBean.DataBean dataBean;

    public static OnADateInfoFragment newInstance(String info) {
        OnADateInfoFragment onADateInfoFragment = new OnADateInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("info", info);
        onADateInfoFragment.setArguments(bundle);
        return onADateInfoFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int setView() {
        return R.layout.frgment_on_a_date_info;
    }

    @Override
    protected void init(View view) {
        backIv = view.findViewById(R.id.layout_head_back_iv);
        titleTv = view.findViewById(R.id.layout_head_title_tv);
        rightTv = view.findViewById(R.id.layout_head_right_tv);
        rightIv = view.findViewById(R.id.layout_head_right_iv);

        userImgIv = view.findViewById(R.id.date_info_user_head_img);
        contactIv = view.findViewById(R.id.date_info_contact_iv);
        userNameTv = view.findViewById(R.id.date_info_user_head_name);
        userYearTv = view.findViewById(R.id.date_info_user_year);
        contantTv = view.findViewById(R.id.date_info_contant);
        addressTv = view.findViewById(R.id.date_info_address);
        timeTv = view.findViewById(R.id.date_info_date_time);
        whyPayTv = view.findViewById(R.id.date_info_why_pay);
        joinTv = view.findViewById(R.id.date_info_join_tv);
        appraiseTv = view.findViewById(R.id.date_info_appraise_tv);

        mRecyclerView = view.findViewById(R.id.date_info_xrv);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setArrowImageView(R.mipmap.iconfont_downgrey);

        mRecyclerView
                .getDefaultRefreshHeaderView()
                .setRefreshTimeVisible(true);
        mRecyclerView.getDefaultFootView().setLoadingHint("自定义加载中提示");
        mRecyclerView.getDefaultFootView().setNoMoreHint("自定义加载完毕提示");
        mRecyclerView.setLimitNumberToCallLoadMore(1);
        mRecyclerView.setLoadingListener(this);

        mRecylerAdapter = new RecyclerAdapter<FoundDynamicBean.DataBean>(mItemListener) {
            @Override
            public ItemWrapper getItemHolder(int position) {
                return new ItemWrapper(R.layout.item_dynamic,OnADateInfoAdapter.class);
            }
        };
        mRecyclerView.setAdapter(mRecylerAdapter);

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        Log.i("OnADateInfoFragment", getArguments().getString("info"));
        dataBean = new Gson().fromJson(getArguments().getString("info"), HomeActivityDataBean.DataBean.class);
        dateInfo(dataBean.getEventid(), 1);
        rightIv.setVisibility(View.VISIBLE);
        rightTv.setVisibility(View.GONE);
        titleTv.setText("正在约会");

        Glide.with(getActivity()).load(dataBean.getHeadimg()).asBitmap().error(R.mipmap.user_pic).placeholder(R.mipmap.user_pic).into(userImgIv);
        contantTv.setText(dataBean.getEventexplain());
        userNameTv.setText(dataBean.getNickname());
        userYearTv.setText(dataBean.getBirthday());
        addressTv.setText(dataBean.getPlacename());
        timeTv.setText(dataBean.getEventdate());
        whyPayTv.setText(dataBean.getCtname());
        rightIv.setImageResource(R.mipmap.more_icon);
        backIv.setOnClickListener(this);
        rightIv.setOnClickListener(this);
        contactIv.setOnClickListener(this);
        joinTv.setOnClickListener(this);
        appraiseTv.setOnClickListener(this);

        queryIsJoin(dataBean.getEventid());
    }

    private OnItemListener mItemListener = new OnItemListener() {
        @Override
        public void onItemClick(View view, int position) {

        }
    };

    /**
     * 查询是否参加活动
     */
    private void queryIsJoin(int eventid){
        HttpUtils.doGet(HttpContant.URL + HttpContant.QueryIsJoin + "?eventid=" + eventid
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("IsJoin", response.body().string()));
                    }
                });
    }
    /**
     * 活动内评论请求
     */
    private void dateInfo(int eventid, int page) {
        HttpUtils.doGet(HttpContant.URL + HttpContant.QueryDateInfoAppraise + "?eventid=" + eventid + "&&page=" + page
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("dateInfoAppraise", response.body().string()));
                    }
                });
    }

    /**
     * 报名参加活动
     * @param
     */
    private void joinActivity(int eventid){
        Map<String,Object> map = new HashMap<>();
        map.put("eventid",eventid);
        HttpUtils.PutCookie(HttpContant.URL + HttpContant.JoinDate
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                ,map
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("JoinActivity", response.body().string()));
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBus(NoticeEvent event) {
        switch (event.getCls()) {
            case "requestFail":
                TastyToast.makeText(getActivity(), "请求失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                break;
            case "dateInfoAppraise":
                Log.i("dateInfoAppraise",event.getData().toString());
                break;
            case "IsJoin":
                Log.i("IsJoin",event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        if (object.getInt("data") == 0){
                            joinTv.setText("报名");
                            joinTv.setEnabled(true);
                        }else if (object.getInt("data") == 1){
                            joinTv.setEnabled(false);
                            joinTv.setText("已报名");
                        }
                    }else {
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case "JoinActivity":
                Log.i("JoinActivity",event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        joinTv.setText("已报名");
                        joinTv.setEnabled(false);
                        TastyToast.makeText(getActivity(),object.getString("data"),TastyToast.LENGTH_SHORT,TastyToast.SUCCESS).show();
                    }else {
                        joinTv.setText("报名");
                        joinTv.setEnabled(true);
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case "sendAppraise":
                Log.i("sendAppraise",event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        TastyToast.makeText(getActivity(),object.getString("data"),TastyToast.LENGTH_SHORT,TastyToast.SUCCESS).show();
                        mPopWindow.dismiss();
                        dateInfo(dataBean.getEventid(),1);
                    }else {
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_head_back_iv:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
            case R.id.layout_head_right_iv:
                break;
            case R.id.date_info_contact_iv:
                //发起点对点聊天
                String recipients = null;
                try {
                    recipients = AESOperator.getInstance().decrypt(dataBean.getPhone());
                    Log.i("OnADateInfoFragment",recipients);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (TextUtil.isEmpty(recipients)) {
                    return;
                }
                IMPluginManager.getManager().startChatting(getActivity(), recipients);
                break;
            case R.id.date_info_join_tv:
                if (joinTv.getText().toString().equals("报名")){
                    joinActivity(dataBean.getEventid());
                }
                break;
            case R.id.date_info_appraise_tv:
                showPopupWindow();
                break;
        }
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {

    }

    interface OnItemListener {
        void onItemClick(View view, int position);
    }

    static class OnADateInfoAdapter extends RecyclerHolder<FoundDynamicBean.DataBean> {

        private TextView releaseTimeTv,nameTv,yearTv,contantTv,addressTv,browseTv,commentsTv,giveLikeTv;
        private ImageView userIv;
        private OnItemListener mItemListener;

        public OnADateInfoAdapter(View itemView, OnItemListener listener) {
            super(itemView);
            userIv = itemView.findViewById(R.id.item_user_iv);
            releaseTimeTv = itemView.findViewById(R.id.item_release_time);
            nameTv = itemView.findViewById(R.id.item_user_name);
            yearTv = itemView.findViewById(R.id.item_dynamic_user_year);
            contantTv = itemView.findViewById(R.id.item_dynamic_contant);
            addressTv = itemView.findViewById(R.id.item_dynamic_address);
            browseTv = itemView.findViewById(R.id.item_dynamic_browse_num);
            commentsTv = itemView.findViewById(R.id.item_dynamic_comments_num);
            giveLikeTv = itemView.findViewById(R.id.item_dynamic_give_like_num);

            mItemListener = listener;
        }

        @Override
        public void onBindView(FoundDynamicBean.DataBean dataBean) {
            releaseTimeTv.setText(String.valueOf(dataBean.getBirthday()));
            nameTv.setText(dataBean.getNickname());
            yearTv.setText("未传");
            contantTv.setText(dataBean.getEssay());
            addressTv.setText(dataBean.getPlacename());
            browseTv.setText("111人");
            commentsTv.setText("111人");
            giveLikeTv.setText("111人");
            Glide.with(userIv.getContext()).load(dataBean.getHeadimg()).asBitmap().error(R.mipmap.user_pic).placeholder(R.mipmap.user_pic).into(userIv);
        }
    }
    /**
     *
     */
    private PopupWindow mPopWindow;
    private EditText editText;
    private TextView sendTv;

    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popup, null);
        mPopWindow = new PopupWindow(contentView,
                ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        //防止PopupWindow被软件盘挡住（可能只要下面一句，可能需要这两句）
//        mPopWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        mPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置软键盘弹出
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(1000, InputMethodManager.HIDE_NOT_ALWAYS);//这里给它设置了弹出的时间
        //设置各个控件的点击响应
        editText = contentView.findViewById(R.id.pop_editText);
        sendTv = contentView.findViewById(R.id.appraise_send_tv);
        sendTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(editText.getText())){
                    TastyToast.makeText(getActivity(),"内容不能为空",TastyToast.LENGTH_SHORT,TastyToast.WARNING).show();
                }else {
                    sendAppraise(editText.getText().toString(),dataBean.getEventid());
                }
            }
        });

        //是否具有获取焦点的能力
        mPopWindow.setFocusable(true);
        //显示PopupWindow
//        View rootview = LayoutInflater.from(getActivity()).inflate(R.layout.activity_main, null);
        mPopWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 发送评论
     */
    private void sendAppraise(String commenttext,int eventid){

        Map<String,Object> map = new HashMap<>();
        map.put("commenttext",commenttext);
        map.put("eventid",eventid);

        HttpUtils.PutCookie(HttpContant.URL + HttpContant.SendAppraise
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , map
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("sendAppraise",response.body().string()));
                    }
                });
    }

}
